package main

import (
	"demo/influxdb/influx"
	"encoding/json"
	"fmt"
	"github.com/influxdata/influxdb/client/v2"
	"time"
)

func main() {
	// 创建客户端
	httpClient, err := influx.NewClient("118.89.29.19:8086", "moyrn", "moyrn")
	if err != nil {
		panic(err)
	}

	// f55800c4-e388-11ea-8001-e09467ae2113
	limit, offset := 10, 0
	for offset = 0; offset < 1000; offset += 10 {
		cmd := fmt.Sprintf("select * from \"%s\" limit %d offset %d", "f55800c4-e388-11ea-8001-e09467ae2113", limit, offset)
		response, err := httpClient.Query(client.Query{
			Command:  cmd,
			Database: "device_data",
		})
		if err != nil {
			panic(err)
		}
		if response.Error() != nil {
			panic(response.Error())
		}

		//fmt.Printf("limit: %d\toffset: %d\t%#v\n", limit, offset, response.Results)
		marshal, _ := json.Marshal(columnsParse(response.Results, limit))
		fmt.Println(string(marshal))
		time.Sleep(time.Second * 3)
	}

}

type Model []map[string]interface{}

// warning 原结构转 []map[string]interface{} 为智障操作，增加了大量的无用数据
func columnsParse(results []client.Result, limit int) Model {
	m := make(Model, 0, limit)
	if len(results) != 0 {
		r := results[0]
		mm := make(map[string]interface{})
		if len(r.Series) != 0 {
			for _, values := range r.Series[0].Values {
				for i, c := range r.Series[0].Columns {
					//fmt.Println("i", i, "c", c, "value", r.Series[0].Values[row][i])
					if c == "time" {
						tt, ok := values[i].(string)
						if !ok {
							panic("not ok")
						}
						parse, err := time.Parse("2006-01-02T15:04:05.999999999Z", tt)
						if err != nil {
							panic(err)
						}
						mm[c] = parse.UnixNano()
						continue
					}
					mm[c] = values[i]
				}
				for k, t := range r.Series[0].Tags {
					mm[k] = t
				}
				m = append(m, mm)
			}
		}
	}
	return m
}
